package xserver.codec;

import java.io.IOException;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderAdapter;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import xgame.AbstractXcommand;
import xgame.XpropertyContainer;
import xserver.XmoduleTManager;

/**
 * 命令解码器
 * 
 * @author AfritXia
 * @version $Rev: 17 $
 *
 */
public class CommandDecoder extends ProtocolDecoderAdapter {
	/**
	 * 序列化器
	 * 
	 */
	private JSONSerializer _serializer = null;

	/**
	 * 类默认构造器
	 * 
	 */
	public CommandDecoder() {
		this._serializer = new JSONSerializer();
	}
	
	@Override
	public void decode(IoSession session, ByteBuffer buff, ProtocolDecoderOutput output) {
		if (buff == null || output == null) {
			return;
		}

		// 创建字节数组
		byte[] bytes = new byte[buff.capacity()];

		try {
			// 将缓存数据读入字节数组
			buff.asInputStream().read(bytes);
		} catch (IOException ex) {
			ex.printStackTrace();
			return;
		}

		XpropertyContainer c = this._serializer.deserialize(bytes);

		if (c == null) {
			return;
		}

		AbstractXcommand cmd = this.getXcommand(c);

		if (cmd == null) {
			return;
		}

		// 清除缓存
		buff.position(buff.limit());
		buff.clear();

		// 写出命令对象
		output.write(cmd);
	}

	/**
	 * 获取命令对象
	 * 
	 * @param c
	 * @return 
	 * 
	 */
	private AbstractXcommand getXcommand(XpropertyContainer c) {
		if (c == null) {
			return null;
		}

		// 获取命令 Id
		int cmdId = c.getInt(AbstractXcommand.COMMAND_ID);

		if (cmdId <= 0) {
			return null;
		}

		// 获取命令本身
		XpropertyContainer bodyC = c.getPropertyContainer(AbstractXcommand.COMMAND_BODY);

		if (bodyC == null) {
			return null;
		}

		// 获取命令对象
		AbstractXcommand cmd = XmoduleTManager.getCommand(cmdId);

		if (cmd == null) {
			return null;
		}

		// 反序列化命令对象
		cmd.deserialize(bodyC);

		return cmd;
	}
}
